package com.csliubo.eclipse.plugin.sqlgenerator.core;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;

import com.csliubo.eclipse.plugin.sqlgenerator.core.model.Table;
import com.csliubo.eclipse.plugin.sqlgenerator.core.processor.SqlProcessor;
import com.csliubo.eclipse.plugin.sqlgenerator.core.writer.DataWriter;

public class DataGenerator {

    public static void generate(File file) throws Throwable {
        Config.init(file);
        ConnectionManager.open();
        CountDownLatch latch = new CountDownLatch(Config.getTableAndSqlMap().size());
        List<Table> tables = getTables(latch);
        latch.await();
        ConnectionManager.close();
        DataWriter writer = OuputTypeFactory.getDataWriter(Config.getOuputFormat());
        writer.write(Config.getTargetFilePath() + "_prepare", tables);
        writer.write(Config.getTargetFilePath() + "_result", tables);
    }

    /**
     * 每个表一个Sqlrocessor，多线程去取数据库内容
     * @param latch countDownLatch用来同步
     * @return
     * @throws Throwable
     */
    private static List<Table> getTables(CountDownLatch latch) throws Throwable {
        Map<String, String> map = Config.getTableAndSqlMap();
        List<Table> tables = new ArrayList<Table>(map.size());
        for (Entry<String, String> entry : map.entrySet()) {
            String tableName = entry.getKey();
            String sql = entry.getValue();
            Table table = new Table(tableName);
            SqlProcessor processor = new SqlProcessor(table, sql, latch);
            processor.start();
            tables.add(table);
        }
        return tables;
    }
}